<?php

namespace app\api\controller\chat;

use thinkct\controller\Frontend;
use app\common\model\chat\ChatGroup;
use app\common\model\chat\ChatMessage;

class Bot extends Frontend
{
    protected array $noNeedLogin = ['index', 'get_group', 'get_message'];

    public function initialize(): void
    {
        parent::initialize();
    }

    public function index(): string
    {
        return 'hello world';
    }

    /**
     * 获取聊天列表
     */
    public function get_group($title = ''): void
    {
        // 获取列表 增加字段 message_num
        $chatList = ChatGroup::where([['title', 'like', $title . '%']])->where(['user_id'=> $this->auth->id, 'status' => 1])
            ->order('update_at', 'desc')->select();
        $this->success('聊天列表', ['list' => $chatList]);
    }

    /**
     * 创建聊天列表
     */
    public function create_group($title = '新的聊天'): void
    {
        // 创建列表
        $chatList = ChatGroup::create(['title'=>$title, 'user_id'=> $this->auth->id, 'status'=>1]);
        $this->success('创建成功', $chatList);
    }

    /**
     * 删除聊天列表
     */
    public function delete_group($id = ''): void
    {
        // 删除列表
        $chatList = ChatGroup::where(['id'=>$id, 'user_id'=> $this->auth->id])->delete();
        if ($chatList) {
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }
    }

    /**
     * 获取聊天内容
     */
    public function get_message($group_id = ''): void
    {
        // 获取聊天内容
        $ChatMessage = ChatMessage::where(['group_id'=>$group_id, 'from_id|to_id'=> $this->auth->id])->select();
        $this->success('聊天内容', ['list'=>$ChatMessage]);
    }

    /**
     * 发送聊天内容
     */
    public function send_text($group_id = '', $content = ''): void
    {
        if($content == ''){
            $this->error('内容不能为空');
        }
        // 检测违禁词
        $wordfilte_status = get_sys_config('wordfilte_status');
        $wordfilter_danger = get_sys_config('wordfilter_danger');
        if($wordfilte_status == 1 && $wordfilter_danger != '') {
            $wordfilter_danger = explode(',', $wordfilter_danger);
            foreach ($wordfilter_danger as $word) {
                if(strpos($content, $word) !== false) {
                    $this->error('内容包含违禁词');
                }
            }
        }

        // 获取分组信息
        $chatList = ChatGroup::where(['id'=>$group_id])->find();
        if(!$chatList){
            $chatList = ChatGroup::create(['title'=>$content, 'user_id'=> $this->auth->id, 'status'=>1]);
            $group_id = $chatList->id;
        } else {
            $chatList->title = $content;
            $chatList->update_at = date('Y-m-d H:i:s');
            $chatList->save();
        }

        $gpt_api_key = get_sys_config('gpt_api_key');
        if(!$gpt_api_key){
            $this->error('请先配置GPT_KEY');
        }
        $chat = new \openai\ChatGPT([
            'api_key' => $gpt_api_key,
        ]);

        // 关联上下文
        $ChatMessage = ChatMessage::where(['group_id'=>$group_id])->field('role, content')->select();
        $messages = [['role' => 'system', 'content' => '你是一个智能助手']];
        foreach ($ChatMessage as $message_item) {
            $item = $message_item->toArray();
            unset($item['avatar']);
            unset($item['nickname']);
            $messages[] = $item;
        }
        $messages[] = ['role' => 'user', 'content' => $content];
        $chat->qa([
            'system' => '你是一个智能机器人',
            'question' => $content,
        ], $messages);
        $messageText = $chat->getAnswer();
        if(!empty($messageText)) {
            ChatMessage::create(['user_id'=>$this->auth->id, 'from_id'=>$this->auth->id, 'group_id'=>$group_id, 'role' => 'user', 'content'=>$content]);
            ChatMessage::create(['user_id'=>$this->auth->id, 'to_id'=>$this->auth->id, 'group_id'=>$group_id, 'role' => 'assistant', 'content'=>$messageText]);
        }
    }
}